package com.zx.cloud.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zx.cloud.ApiVersion;
import com.zx.cloud.Shift;
import com.zx.cloud.common.filter.CurrentUserId;
import com.zx.cloud.common.filter.IgnoreAuth;
import com.zx.cloud.common.qiniu.FileType;
import com.zx.cloud.model.response.ObjectDataResponse;
import com.zx.cloud.security.Base64;
import com.zx.cloud.util.EncodeUtil;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = ApiVersion.API_V1_PREFIX+"/file")
public class FileController {

	/**
	 * 上传文件存储的绝对路径
	 */
	@Value("${upload.absolute.file.path}")
	private String uploadFilePath;
	/**
	 * 访问的base路径
	 */
	@Value("${upload.access.file.path}")
	private String baseServerUrl;
	
	private static int counter = 0;

	private String[] buildFilePath(Long userId,FileType fileType,String fileName_) {
		int slashIndex =fileName_.indexOf(".");
		String fileName=null;
		if (slashIndex >= 0) {
			fileName =fileName_.substring(slashIndex+1);
		}
		
		fileName = EncodeUtil.encodeMD5(userId+""+System.nanoTime() + counter++) + (fileName==null?null:"."+fileName);
		System.out.println("新图片名称："+fileName);
		File file=new File(uploadFilePath,fileType.getCode()+File.separator+userId+File.separator+fileName);
		String httpUrl=baseServerUrl+fileType.getCode()+File.separator+userId+File.separator+fileName;
		httpUrl=httpUrl.replace("\\", "/");
		return new String[]{file.getAbsolutePath(),httpUrl};
	}
	
	@IgnoreAuth
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "Form表单单文件上传", notes = "form表单单文件上传")
	public ObjectDataResponse<String> uploadStaticFile(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestParam MultipartFile file, @RequestParam FileType fileType){
		if (fileType==null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION);
		}
		if (file.isEmpty()) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION);
		}
		String[] filePaths=buildFilePath(userId, fileType,file.getOriginalFilename());
		try {
			File writeFile=new File(filePaths[0]);
			writeFile.setReadable(true);//设置可读权限
			writeFile.setWritable(true);//设置可写权限
			FileUtils.copyInputStreamToFile(file.getInputStream(),writeFile );
		} catch (IOException e) {
			e.printStackTrace();
			Shift.fatal(StatusCode.FILE_UPLOAD_ERROR);
		}
		return new ObjectDataResponse<String>(filePaths[1]);
	}
	
	@RequestMapping(value = "/uploadMuti", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "Form表单多文件上传", notes = "form表单多文件上传")
	public ObjectDataResponse<List<String>> uploadMutiStaticFile(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestParam MultipartFile[] files ,@RequestParam FileType fileType){
		if(files==null||files.length==0) {
			 Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION);
	    }
    	List<String> uploadFiles=new ArrayList<String>();
    	for (MultipartFile multipartFile : files) {
    		if (multipartFile.isEmpty()) {
    			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION);
    		}
    		String[] filePaths=buildFilePath(userId, fileType,multipartFile.getOriginalFilename());
    		try {
    			File writeFile=new File(filePaths[0]);
    			writeFile.setReadable(true);//设置可读权限
    			writeFile.setWritable(true);//设置可写权限
    			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),writeFile );
    		} catch (IOException e) {
    			e.printStackTrace();
    			Shift.fatal(StatusCode.FILE_UPLOAD_ERROR);
    		}
    		uploadFiles.add(filePaths[1]);
		}
    	return new ObjectDataResponse<List<String>>(uploadFiles);
	}

	@RequestMapping(value = "uploadBase64File", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "Base64加密单文件上传", notes = "Base64加密单文件上传")
	public ObjectDataResponse<String> uploadBase64File(@ApiParam(hidden = true, name = "登录用户ID") @CurrentUserId Long userId, @RequestParam FileType fileType,
			@RequestParam String filename, HttpServletRequest servletRequest, String imageFile){
		String imageFile_ = servletRequest.getParameter("imageFile");
		if (StringUtils.isEmpty(imageFile_)) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "imageFile必传");
		}
		if (StringUtils.isEmpty(filename)) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "filename必传");
		}
		byte[] bytes = Base64.decode(imageFile_); // 将字符串转换为byte数组
		String[] filePaths = buildFilePath(userId, fileType, filename);
		try {
			FileUtils.writeByteArrayToFile(new File(filePaths[0]), bytes);
		} catch (IOException e) {
			e.printStackTrace();
			Shift.fatal(StatusCode.FILE_UPLOAD_ERROR);
		}
		return new ObjectDataResponse<String>(filePaths[1]);
	}


}
